package com.ch.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "MathServlet", value = "/MathServlet")
public class MathServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String a = request.getParameter("a");
        final String b = request.getParameter("b");
        String op = request.getParameter("op");
        Integer integerA;
        Integer integerB;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        try {
            integerA = Integer.valueOf(a);
        } catch (NumberFormatException e) {
            response.getWriter().println("请输入正确的参数 a 值");
            return;
        }

        try {
            integerB = Integer.valueOf(b);
        } catch (NumberFormatException e) {
            response.getWriter().println("请输入正确的参数 b 值");
            return;
        }

        if ("+".equals(op)) {
            response.getWriter().println(integerA + integerB);
        } else if ("-".equals(op)) {
            response.getWriter().println(integerA - integerB);
        } else if ("*".equals(op)) {
            response.getWriter().println(integerA * integerB);
        } else if ("/".equals(op)) {
            if (integerB == 0) {
                response.getWriter().println("除数不能为0");
            } else {
                response.getWriter().println(integerA / integerB);
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
